package org.aeon.gamechatnest.service.impl;

import org.aeon.gamechatnest.common.Constant;
import org.aeon.gamechatnest.common.enumeration.LoginStatus;
import org.aeon.gamechatnest.common.response.RespStatus;
import org.aeon.gamechatnest.dto.UserCacheDto;
import org.aeon.gamechatnest.dto.UserVo;
import org.aeon.gamechatnest.exception.ApplicationException;
import org.aeon.gamechatnest.mapper.ServerMembersMapper;
import org.aeon.gamechatnest.mapper.UserServerMapper;
import org.aeon.gamechatnest.pojo.ServerMembers;
import org.aeon.gamechatnest.service.ServerMembersService;
import org.aeon.gamechatnest.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author : Liys 2024/5/13 15:04
 */
@Service
public class ServerMembersServiceImpl implements ServerMembersService {
    @Autowired
    private ServerMembersMapper serverMembersMapper;

    @Autowired
    private UserServerMapper userServerMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    @Transactional(rollbackFor = ApplicationException.class)
    public boolean join(ServerMembers serverMembers) {

        // 新建服务器成员
        serverMembers.setJoinTime(new Date());

        // 执行添加
        if (serverMembersMapper.add(serverMembers) != 1) {
            throw new ApplicationException(RespStatus.FAIL, "加入失败，请联系管理员！");
        }
        return true;
    }

    /**
     * 通过服务器和用户id删除服务器成员
     *
     * @param serverId
     * @param userId
     * @return
     */
    @Override
    public boolean removeById(Long serverId, Long userId) {
        return serverMembersMapper.deleteById(serverId, userId) > 0;
    }

    /**
     * 修改服务器下用户的备注名
     *
     * @param serverMembers
     * @return
     */
    @Override
    public boolean modifyNoteName(ServerMembers serverMembers) {
        return serverMembersMapper.updateNoteName(serverMembers) > 0;
    }

    /**
     * 通过服务器id查询指定服务器下的所有用户
     *
     * @param serverId 服务器id
     * @return 用户视图列表
     */
    @Override
    public List<UserVo> getAllByServerId(Long serverId) {
        return serverMembersMapper.getAllByServerId(serverId);
    }

    @Override
    public List<Long> getUserIdByServerId(Long serverId) {
        return serverMembersMapper.getUserIdByServerId(serverId);
    }

    @Override
    public List<UserVo> getOnLineByServerId(Long serverId) {
        List<UserVo> userVos = getAllByServerId(serverId);
        // 过滤掉不在线的用户和隐身用户
        return userVos.parallelStream().filter(userVo -> {
            UserCacheDto userCacheDto = redisCache.getCacheObject(Constant.USER_TOKEN_CACHE_PREFIX + userVo.getUserId());
            return userCacheDto.getLoginStatus() == LoginStatus.ONLINE;
        }).toList();
    }
}
